package com.bwc.aidemo.viewmodel

import android.app.Application
import android.content.Intent
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.mojawa.mj_amap.item.SubsectionDistionItem
import com.mojawa.mj_util.gps.GpsSignalStrength


import com.mojawa.mj_util.time.MJTimeUtil
import com.mojawa.mj_util.time.MJTimeManager

class AmapViewModel(application: Application) : AndroidViewModel(application) {

    private val _gpsSignalStrength = MutableLiveData<GpsSignalStrength>()
    val gpsSignalStrength: LiveData<GpsSignalStrength> get() = _gpsSignalStrength

    private val _totalDistance = MutableLiveData<Double>()
    val totalDistance: LiveData<Double> get() = _totalDistance

    private val _timeElapsed = MutableLiveData<String>()
    val timeElapsed: LiveData<String> get() = _timeElapsed

    // 公里数据的 LiveData 列表
    private val _kilometerDataList = MutableLiveData<MutableList<SubsectionDistionItem>>()
    val kilometerDataList: LiveData<MutableList<SubsectionDistionItem>> get() = _kilometerDataList

    private var lastRecordedDistance = 0.0  // 上一次记录的总距离
    private var lastKilometerTime: Long = 0L  // 上一个1公里的时间戳
    private var totalDuration: Long = 0L  // 总时间（秒）
    private var kilometerCount = 0  // 记录第几公里

    val timerManager = MJTimeManager.getInstance()
    private val handler = Handler(Looper.getMainLooper())
    private val updateTimeRunnable = object : Runnable {
        override fun run() {
            _timeElapsed.postValue(MJTimeUtil.longToTimeString(timerManager.getSeconds()))
            handler.postDelayed(this, 1000)
        }
    }

    init {
        // 开始计时
        _kilometerDataList.value = mutableListOf()  // 初始化为空列表
        startTimer()
    }

    private fun startTimer() {
        handler.post(updateTimeRunnable)
    }

    fun updateDistance(distance: Double) {
        _totalDistance.postValue(distance)
    }

    fun pauseTimer() {
        MJTimeUtil.isPaused = true
        timerManager.pauseTimer()
    }

    fun destroy(){
        timerManager.stopAndDestroyTimer()
    }

    fun resumeTimer() {
        MJTimeUtil.isPaused = false
        MJTimeUtil.isFirstLocationAfterResume = true
        timerManager.resumeTimer(object : MJTimeManager.TimerUpdateListener {
            override fun onTimerUpdate(seconds: Long) {
                _timeElapsed.postValue(MJTimeUtil.longToTimeString(seconds))
            }
        })
    }

    fun updateGpsSignal(signalStrength: GpsSignalStrength) {
        _gpsSignalStrength.postValue(signalStrength)
    }




    fun updateDistanceAndCalculatePace(currentTotalDistance: Double) {
        // 计算自上次记录以来行进的距离
        val distanceSinceLastUpdate = currentTotalDistance - lastRecordedDistance

        // 检查是否跨越了1公里
        if (distanceSinceLastUpdate >= 1000) {
            val currentTime = timerManager.getSeconds()
            kilometerCount++

            // 计算当前公里花费的时间（秒）
            val oneKilometerTime = currentTime - lastKilometerTime

            // 计算当前公里的配速
            val currentPace = MJTimeUtil.calculatePace(oneKilometerTime, 1.0)

            // 更新总时长
            totalDuration += oneKilometerTime
            val totalDurationString = MJTimeUtil.longToTimeString(totalDuration)

            // 构建新的公里数据
            val newKilometerData = SubsectionDistionItem(
                kilometre = kilometerCount,
                speedAllocation = currentPace,
                cumulativeDuration = totalDurationString
            )

            // 更新公里数据列表
            val updatedList = _kilometerDataList.value ?: mutableListOf()
            updatedList.add(newKilometerData)
            _kilometerDataList.postValue(updatedList)

            // 更新上一次记录的距离和时间
            lastRecordedDistance += 1000  // 更新为跨越的1公里
            lastKilometerTime = currentTime
        }
    }

}

